<?php

namespace App\Recharge\Api;

use App\Models\InterfaceConfiguration;
use App\Recharge\Bean\ApiNotifyDataBean;
use App\Recharge\Bean\BasicInformation;
use App\Recharge\Interfaces\ApiInterface;
use GuzzleHttp\Promise\PromiseInterface;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\Pool;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class Yipai extends AbstractApi
{
    /**
     * @param array $array
     * @param string $secret_key
     * @return string
     */
    public function sign(array $array, string $secret_key): string
    {
        $str = $array['businessId'] . $array['userOrderId'] . $array['goodsId'] . $array['goodsNum'] . $array['orderIp'];
        //生成的sign签名
        return md5(strtolower($str) . $secret_key);
    }

    /**
     * @inheritDoc
     */
    public function rechargeData(BasicInformation $bean): array
    {
        $array = [
            'businessId'    => $bean->getSupplierNum(), //商户号
            'userOrderId'   => $bean->getOrderNo(), //订单号
            'goodsId'       => $bean->getGoodsId(), //商品编号id
            'userName'      => $bean->getAccount(), //要充值的用户
            'gameType'      => $bean->getGameType(), //充值的类型
            'goodsNum'      => $bean->getRechargeNum(), //充值数量
            'orderIp'       => $bean->getIp(), //获取用户当前的ip
            'unitPrice'     => $bean->getUnitPrice(), //商品的单价
            'gameName'      => $bean->getGoodsName(), //游戏名称
            'gameAcct'      => $bean->getGameAcct(), //游戏账号
            'gameArea'      => $bean->getGameAreaName(), //游戏区服
            'acctType'      => $bean->getAccountType(), //账号类型
            'noticeUrl'     => $bean->getNotifyUrl(), //异步回调地址
        ];
        $array['sign'] = $this->sign($array, $bean->getSecretKey());

        return $array;
    }

    /**
     * @param InterfaceConfiguration $api
     * @param Request $request
     * @return ApiNotifyDataBean
     */
    public function apiNotifyLogic(InterfaceConfiguration $api, Request $request): ApiNotifyDataBean
    {
        $status = $request->input('status', '');
        $order_sn = $request->input('userOrderId', '');
        return $this->apiNotifyData($order_sn, $status)->setExecute(true)->setRechargeSuccess($status == 1);
    }

    /**
     * @return Application|ResponseFactory|Response
     */
    public function apiNotifySuccess(): Application|ResponseFactory|Response
    {
        return response('<receive>ok</receive>', headers: ['content-type' => 'application/xml; charset=utf-8']);
    }
}
